/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.sql.*;

import java.util.logging.Logger;


public class Login extends Servlet0
{
	@SuppressWarnings("unused")
	private static Logger theLogger = Logger.getLogger(Login.class.getName());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1143657164028754495L;

	protected void initStmt()
	{
		ps_new = DBConn.stmt("insert into Profile(login,password)"
				+ " values (?,md5(?))");

		ps_check = DBConn.stmt("select idProfile from Profile"
				+ " where login=? and password=md5(?)");
	}

	private String doNew(String login, String password) throws Exception
	{
		ps_new.clearParameters();
		ps_new.setString(1, login);
		ps_new.setString(2, password);
		ps_new.executeUpdate();

		return "";
	}

	private String checkAuth(String login, String password) throws Exception
	{
		ps_check.setString(1, login);
		ps_check.setString(2, password);

		ResultSet rs = ps_check.executeQuery();
		if (!rs.next()) throw new Exception("Auth failed");

		String id = rs.getString(1);

		rs.close();
		return id;
	}

	private String doLogin(String login, String password) throws Exception
	{
		String id = checkAuth(login, password);
		String key = Auth.register(id);

		return id + "\n" + key;
	}

	protected String handle() throws Exception
	{
		String action = param("action");
		String login = param("login");
		String password = param("password");
		String ret = null;

		if (action.equals("new")) {
			ret = "1";
			ret = doNew(login, password);
			ret += "2";
		}
		if (action.equals("login")) ret = doLogin(login, password);

		if (ret == null) throw new Exception("invalid action");
		return ret;
	}
}
